package com.cat.binaryTree;

import java.util.List;

/**
 * @author 曲大人的喵
 * @description public ListNode reverseBetween(ListNode head, int left, int right) {              }
 * @create 2025/9/13 19:10
 * @since JDK17
 */

public class Solution31 {
    ListNode reverse(ListNode head) {
        ListNode pre = null, cur = head, next = head;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode l = null, r = null, newHead = new ListNode(-1, head), p = newHead;
        for (int i = 0; p != null; i++, p = p.next) {
            if (i == left - 1) {
                l = p;
            }
            if (i == right) {
                r = p;
            }
        }
        ListNode next = r.next;
        r.next = null;
        l.next = reverse(l.next);
        while (l.next != null) l = l.next;
        l.next = next;
        return newHead.next;
    }
}
